#include <iostream>
#include <unistd.h>
#include <fstream>
#include <string>
#include <mysql/mysql.h>
#include <cstring>
#include <errno.h>

void pase_brief(std::string& brief, const std::string& content, int size)
{
    int cur = content.find("<p>") + 3;
    int end = content.find("</p>");

    while (brief.size() < size && cur < end)
    {

        if (content[cur] == '<')
        {
            while (content[cur++] != '>');
            brief += ",";
        }

        brief += content[cur++];
    }
}

// 创建blog_list
int create_list(std::string& order, char* id, char* title, char* content)
{
    std::string _1 = "<li class=\"cont-req2\">"
                    "<a href=\"javascript:;\" class=\"t2_pick\"><img src=\"images/404-2.png\" alt=\"\"></a>"
                    "<div class=\"lvti\">"
                    "    <h2><a href=\"javascript:;\">";

    _1 += title; //标题
    _1.append("</a></h2>"
                        "<div class=\"content\">");
    std::string brief;
    pase_brief(brief, content, 50);
    _1.append(brief); // 前50个字
    _1 += "......";

    // 填写'阅读网址参数'
    std::string _2 = "</div>"
                        "<ul class=\"entry-meta\">"
                           " <li>"
                             "   <i class=\"iconfont\">&#xe601;</i>"
                              "  <a href=\"cgi_sql/blog_del_sql.cgi?blogId=";
    _1.append(_2);
    _1 += id;
    std::string _2_5    = "\">删除文章</a>"
                           " </li>"
                            "<li>"
                                "<i class=\"iconfont\">&#xe60b;</i>"
                                "<a href=\"javascript:;\">2018-12-18</a>"
                            "</li>"
                            "<li>"
                                "<i class=\"iconfont\">&#xe652;</i>"
                                "<a href=\"javascript:;\">阿峰</a>"
                            "</li>"
                            "<li class=\"btn-Msg\">"
                                "<a href=\"cgi_sql/blog_r_sql.cgi?blogId=";
    _1.append(_2_5);
    _1 += id;   // 文章主键
    std::string _3 = "\">阅读全文</a>" //结尾
                            "</li>"
                        "</ul>"
                    "</li>";
    _1 += _3;
    order = _1;
}



int main()
{
    std::string methon = getenv("METHOD");
    std::string paramenter; //CGI 获取目标文章的主键，这里就只有目标文章的主键

    int post_length = 0;
    if (methon == "GET")
    {
        paramenter = getenv("PARAMENTER");
    }else if (methon == "POST")
    {
        //1.获取先出发来CGI的参数信息
        post_length = atoi(getenv("CONTENT-LENHTH"));
        while (post_length > 0)
        {
            char x = 'g';
            int bx =  read(0, &x, 1);
            if (bx == -1)
                std::cerr << strerror(errno) << std::endl;

            paramenter.push_back(x);
            post_length--;
        }
    }
 
    //2.index,就是获取最前面的数据，因此不用解析
    

    //登录连接数据库
    MYSQL *conn;
    MYSQL_RES *result;

    const char *server = "xxxxx";
    const char *user = "afeng";
    const char *password = "xxxx";
    const char *database = "blog_system";
    conn = mysql_init(NULL);

    if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
        std::cerr << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return 1;
    }
    mysql_set_character_set(conn, "utf8");
    // 指令
    std::string str = "select blogId, title, content from blog limit 0, 7";
    if (mysql_query(conn, str.c_str())) {
        std::cerr << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return 1;
    }
    // 得到文章基本信息
    result = mysql_store_result(conn);
    if (result == NULL) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        mysql_close(conn);
        return 1;
    }
    
    int num_line = mysql_num_rows(result);
    int num_field = mysql_num_fields(result);

     //文章正文拼接
    std::string body;
    //拼接头
    std::ifstream infile("CGI/blog_r_list_01.html");
    if (!infile.is_open()) {
        std::cerr << "Failed to open file" << std::endl;
        return 1;
    }
    std::string room;
    while (std::getline(infile, room)) body+=room;
    infile.close();

    // 获取每行列数据
    MYSQL_ROW line = 0;
    for (int n = 0; n < num_line; n++)
    {
        std::string tmp;
        line = mysql_fetch_row(result);
        create_list(tmp, line[0], line[1], line[2]);
        body.append(tmp);
    }

    //拼接尾
    std::ifstream infile2("CGI/blog_r_list_02.html");
    if (!infile2.is_open()) {
        std::cerr << "Failed to open file" << std::endl;
        return 1;
    }
    std::string line2;
    while (std::getline(infile2, line2)) body += line2;
    infile2.close();

    std::cout << "Content-Type: text/html; charset=utf-8\r\r"; 
    // 向父进程发送正文
    std::cout << body << std::endl;//设置终止符

    mysql_free_result(result);
    mysql_close(conn);


    //马上退出，有没有都差不多
    if (methon == "POST")
    {
        close(1);
        close(0);
    }
    return 0;
}